var method = {}


/**
 * @method distance
 * @description_Chinese 计算两个经纬度之间的距离
 * @description_EngList Calculate the distance between latitude and longitude
 * @param {Number} la1 第一个点的纬度
 * @param {Number} lo2 第一个点的经度
 * @param {Number} la2 第二个点的纬度
 * @param {Number} lo2 第二个点的经度
 * @returns {String}
 */
method.distance = (la1, lo1, la2, lo2) => {
  var La1 = la1 * Math.PI / 180.0;
  var La2 = la2 * Math.PI / 180.0;
  var La3 = La1 - La2;
  var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;
  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math
    .sin(Lb3 / 2), 2)));
  s = s * 6378.137; //地球半径
  s = Math.round(s * 10000) / 10000;
  return s;
}
method.compare = (property, order = 'desc') => {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    if (order == 'asc') {
      return value1 - value2;
    }
    if (order == 'desc') {
      return value2 - value1;
    }
  }
}
//去除富文本的特殊符号
method.quhtml = (msg) => {
  var msg = msg.replace(/<\/?[^>]*>/g, ''); //去除HTML Tag
  msg = msg.replace(/[|]*\n/, ''); //去除行尾空格
  msg = msg.replace(/&npsp;/gi, ''); //去掉npsp
  return msg;
}
//获取当前时间戳 到毫秒
method.newdate1000 = () => {
  return Math.round(new Date())
}
//获取当前时间戳
method.mathround = () => {
  return Math.round(new Date() / 1000)
}
//将时间戳转化为时间--y
method.datey = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear();
  return Y;
}
//将时间戳转化为时间--M
method.dateM = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let M = date.getMonth() + 1;
  return M;
}

//将时间戳转化为时间--d
method.dated = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let d = date.getDate();
  return d;
}

//将时间戳转化为时间--y-m-d
method.dateym = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear() + '/';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  return Y + M;
}
//将时间戳转化为时间--y-m-d
method.dateymd = (time, separate = '/') => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear() + separate;
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + separate;
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return Y + M + D;
}

//将时间戳转化为时间--y年m月d日
method.dateymdnyr = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear() + '年';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';
  return Y + M + D;
}
//将时间戳转化为时间--y-m-d h:i:s
method.dateymdhis = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear() + '/';
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
}
//将时间戳转化为时间--y-m-d h:i
method.dateymdhi = (time, decollator = '/') => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let Y = date.getFullYear() + decollator;
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + decollator;
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  return Y + M + D + h + m;
}
//将时间戳转化为时间-- h:i:s
method.datehis = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
  let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  return h + m + s;
}
//将时间戳转化为时间-- M-D h:i
method.datemdhi = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
  return M + D + h + m;
}

//将时间戳转化为时间-- M-D
method.datemd = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
  let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
  return M + D;
}

//将时间戳转化为时间-- h:i
method.datehi = (time) => {
  var date = time ? new Date(time * 1000) : new Date(method.newdate1000());
  let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
  let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());

  return h + m;
}
//将时间转化为时间戳
method.oldtime = (times) => {
  var oldTime = (new Date(times)).getTime() / 1000;
  return oldTime;
}
//根据时间戳计算天数
method.utc = (start) => {
  var end = method.mathround(); //2017-5-10 10:00
  var utc = end - start;
  return Math.ceil(utc / (24 * 60 * 60)); // 天
}
//计算字符长度
method.getlength = (str) => {
  return str.replace(/[\u0391-\uFFE5]/g, 'aa').length; //先把中文替换成两个字节的英文，在计算长度
}

//获取文件名称
method.imgname = (img) => {
  var gang = img.lastIndexOf('/')
  var length = img.length
  return img.slice(gang, length)
}

//将二位数组中的时间戳转化为时间 具体转化的格式调用以上对应的实践转化
method.datamdhi = (data, time = 'createtime') => {
  for (var i = 0; i < data.length; i++) {
    data[i][time] = method.datemdhi(data[i][time])
  }
  return data;
}
//js计算时间为刚刚、几分钟前、几小时前、几天前··
method.timeago = (dateTimeStamp) => { //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
  if (dateTimeStamp.toString().length == 10) {
    var dateTimeStamp = dateTimeStamp * 1000
  }
  var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime(); //获取当前时间毫秒
  var diffValue = now - dateTimeStamp; //时间差
  var result = '';
  if (diffValue < 0) {
    var datetime = new Date();
    datetime.setTime(dateTimeStamp);
    var Nyear = datetime.getFullYear();
    var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
    var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    result = Nyear + "-" + Nmonth + "-" + Ndate
    return result;
  }

  var minC = diffValue / minute; //计算时间差的分，时，天，周，月
  var hourC = diffValue / hour;
  var dayC = diffValue / day;
  var weekC = diffValue / week;
  var monthC = diffValue / month;
  //此处考虑小数情况，感谢 情非得已https://blog.csdn.net/weixin_48495574 指正
  if (monthC >= 1 && monthC < 4) {
    result = " " + parseInt(monthC) + "月前"
  } else if (weekC >= 1 && weekC < 4) {
    result = " " + parseInt(weekC) + "周前"
  } else if (dayC >= 1 && dayC < 7) {
    result = " " + parseInt(dayC) + "天前"
  } else if (hourC >= 1 && hourC < 24) {
    result = " " + parseInt(hourC) + "小时前"
  } else if (minC >= 1 && minC < 60) {
    result = " " + parseInt(minC) + "分钟前"
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = "刚刚"
  } else {
    var datetime = new Date();
    datetime.setTime(dateTimeStamp);
    var Nyear = datetime.getFullYear();
    var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1;
    var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours();
    var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes();
    var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds();
    result = Nyear + "-" + Nmonth + "-" + Ndate
  }
  return result;
}

//js中截取小数点后位数的三种方法
//不四舍五入 通过indexOf方法判断出‘.’在传入值得索引然后利用substring方法直接截取相应的位数
method.getBitindexOf = (value, bit = 3) => {
  let str = value.toString();
  let strIndex = str.indexOf('.');
  if (strIndex === -1) return str;
  str = str.substring(0, strIndex + bit);
  return str;
}
//四舍五入 通过toFixed（）方法直接截取小数点后面的位数。
method.getBittoFixed = (value, bit = 3) => {
  let str = Number(value);
  str = str.toFixed(bit)
  return str;
}
//不四舍五入 通过replace（）方法匹配字符串直接截取
method.getBitreplace = (value) => {
  const reg = /([0-9]+\.[0-9]{2})[0-9]*/;
  let str = value.toString();
  str = str.replace(reg, "$1");
  return str;
}
// //判断是否为https或http
// method.checkurl = (URL) => {
//   var str = URL,
//     Expression = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/,
//     objExp = new RegExp(Expression);
//   if (objExp.test(str) == true) {
//     return true
//   } else {
//     return false
//   }
// }
//获取某个时间的月有多少天
method.monthdaynum = (time) => {
  var time = time || method.mathround()
  var Y = method.datey(time)
  var M = method.dateM(time)
  var day = new Date(Y, M, 0);
  return day.getDate()
}
//获取某个时间的月有多少天
method.monthdaynumym = (Y, M) => {
  var time = method.monthymfirst(Y, M)
  return method.monthdaynum(time)
}
//js获取一个时间是今年的第几周 默认为当前时间
method.dijizhou = (time) => {
  var d1 = time || method.mathround()
  var d2 = method.oldtime(method.datey(method.mathround()) + '/01/01 00:00:00')
  var rq = d1 - d2;
  var s1 = Math.ceil(rq / (24 * 60 * 60));
  var s2 = Math.ceil(s1 / 7);
  return s2;
}

//将某个时间转化为周几
method.chineweek = (time) => {
  var time = time || method.mathround()
  var weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  var week = method.weekdaynum(time)
  return weeks[week]
}
//将某个月转化为英文
method.chinemonth = (time) => {
  var time = time || method.mathround()
  var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October',
    'November', 'December'
  ]
  var month = method.dateM(time)
  return months[month - 1]
}
//获取一个时间的本年的开始时间  默认为当前时间
method.yearfirsttime = (time) => {
  var time = time || method.mathround()
  var Y = method.datey(time)
  var firsttime = method.oldtime(Y + '/01/01 00:00:00')
  return firsttime
}
//获取一个时间的本年的结束时间  默认为当前时间
method.yearendtime = (time) => {
  var time = time || method.mathround()
  var end = method.datey(time)
  var endtime = method.oldtime((Number(end) + 1) + '/01/01 00:00:00') - 1
  return endtime
}
//获取一个时间的本月的开始时间  默认为当前时间
method.monthfirst = (time) => {
  var time = time || method.mathround()
  var Y = method.datey(time)
  var M = method.dateM(time)
  var firsttime = method.oldtime(Y + '/' + M + '/01 00:00:00')
  return firsttime
}
//获取一个时间的本月的结束时间  默认为当前时间
method.monthend = (time) => {
  var time = time || method.mathround()
  var Y = method.datey(time)
  var M = method.dateM(time)
  if (M == 12) {
    Y++
    M = 0
  }
  var endtime = method.oldtime(Y + '/' + (M + 1) + '/01 00:00:00') - 1
  return endtime
}

//获取一个时间在当天的开始时间 默认为当前时间
method.dayfirst = (time) => {
  var time = time || method.mathround()
  var day = method.dateymd(time)
  return method.oldtime(day + ' 00:00:00')
}

//获取一个时间在当天的结束时间 默认为当前时间
method.dayend = (time) => {
  var time = time || method.mathround()
  var day = method.dateymd(time)
  return method.oldtime(day + ' 23:59:59')
}

//获取一个时间的本周的开始时间  默认为当前时间
method.weekfirst = (time) => {
  var now = new Date(method.dateymdhis(time));
  var nowTime = now.getTime();
  var day = now.getDay();
  var longTime = 24 * 60 * 60 * 1000;
  var oneweektime = 6 * 86400 * 1000
  if (day == 0) {
    day = 7
  } else {
    day--
  }

  var dd = nowTime - day * longTime;
  var weenendday = Math.ceil(dd / 1000);
  return method.dayfirst(weenendday)
}

//获取一个时间的本周的结束时间  默认为当前时间
method.weekend = (time) => {
  var now = new Date(method.dateymdhis(time));
  var nowTime = now.getTime();
  var day = now.getDay();
  var longTime = 24 * 60 * 60 * 1000;
  var oneweektime = 86400 * 1000
  var dd = nowTime + (7 - day) * longTime;
  var weenendday = Math.ceil(dd / 1000);
  return method.dayend(weenendday)
}

//根据年份和月份计算这个月的开始时间
method.monthymfirst = (Y, M) => {
  var time = method.monthfirst(method.oldtime(Y + '/' + M + '/01'))
  return time;
}
//根据年份和月份计算这个月的结束时间
method.monthymend = (Y, M) => {
  var time = method.monthend(method.oldtime(Y + '/' + M + '/01'))
  return time;
}
//查看某个时间星期几
method.weekdaynum = (time) => {
  var time = time || method.mathround()
  // var yearfirsttime = method.weekend(method.yearfirsttime(time))
  // var sheng = time - yearfirsttime
  // var weeknum = Math.ceil(sheng / 7 / 86400) * 7 * 86400
  // var a = sheng - weeknum
  // var day = Math.ceil(a / 86400)

  var now = new Date(method.dateymdhis(time));
  var nowTime = now.getTime();
  var day = now.getDay();
  return day;
}

method.toChinesNum = (times) => {
  var chinese = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  var date = times ? new Date(method.dateymdhis(times)) : new Date(method.dateymdhis());
  var y = date.getFullYear().toString();
  var m = date.getMonth().toString();
  var result = "";
  for (var i = 0; i < y.length; i++) {
    result += chinese[y.charAt(i)];
  }
  result += "年";
  if (m.length == 2) {
    if (m.charAt(0) == "1") {
      result += ("十" + chinese[(Number(m.charAt(1))) + 1] + "月");
    }
  } else {
    result += (chinese[(m.charAt(1) + 1)] + "月");
  }
  return result;
}

//设置缓存的过期时间
method.storageseconds = (key, value, seconds) => {
  var timestamp = Date.parse(new Date()) / 1000
  if (key && !value) {
    //删除缓存
    //获取缓存
    var valexpire = uni.getStorageSync(key + '_expire');
    var val = uni.getStorageSync(key);
    if (!val || timestamp >= valexpire) {
      uni.removeStorageSync(key)
      uni.removeStorageSync(key + '_expire')
      return ""
    } else {
      return val
    }
  } else if (key && value) {
    //设置缓存
    if (!seconds) {
      var expire = timestamp + (3600 * 24 * 28)
    } else {
      var expire = timestamp + seconds
    }
    uni.setStorageSync(key, value);
    uni.setStorageSync(key + '_expire', expire);
  } else {
    //("key不能空")
  }
}
//随机生成一个颜色
method.getRandomColor = () => {
  var randColor = (Math.random() * 0xFFFFFF << 0).toString(16);
  while (randColor.length < 6) {
    randColor = "0" + randColor;
  }
  return "#" + randColor;
}

//检测该软件是否打开了通知权限
method.judgePlatForm = () => {
  let platform = uni.getSystemInfoSync().platform
  if (platform == 'ios') {
    var isOn = undefined;
    var types = 0;
    var app = plus.ios.invoke('UIApplication', 'sharedApplication');
    var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
    if (settings) {
      types = settings.plusGetAttribute('types');
      plus.ios.deleteObject(settings);
    } else {
      types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
    }
    plus.ios.deleteObject(app);
    isOn = (0 != types);
    return isOn
  } else if (platform == 'android') {
    //('我是安卓')
  }
}
//跳转到响应的商店给个好评   //应用链接    包名
method.openMarket = (appurl, marketPackageName) => {
  // var appurl;
  // if (plus.os.name == "Android") {
  // 	appurl = "market://details?id=io.dcloud.HelloH5"; //由于hello uni-app没有上Android应用商店，所以此处打开了另一个示例应用
  // } else {
  // 	appurl = "itms-apps://itunes.apple.com/cn/app/hello-uni-app/id1417078253?mt=8";
  // }
  if (typeof (marketPackageName) == "undefined") {
    plus.runtime.openURL(appurl, function (res) {
      //(res);
    });
  } else { //强制指定某个Android应用市场的包名，通过这个包名启动指定app
    if (plus.os.name == "Android") {
      plus.runtime.openURL(appurl, function (res) {
        plus.nativeUI.alert("本机没有安装应用宝");
      }, marketPackageName);
    } else {
      plus.nativeUI.alert("仅Android手机才支持应用宝");
    }
  }
}
method.format2Array = (str, max = 150) => {
  var temp = str.split(/[\n,，：:.;。？?！]/g);
  for (var i = 0; i < temp.length; i++) {
    if (temp[i] == "") {
      temp.splice(i, 1);
      //删除数组索引位置应保持不变
      i--;
    }
  }
  return temp
}

// 根据日期计算年龄
method.getage = (strBirthday) => {
  //strBirthday传入格式 2020-04-15
  var returnAge;
  var strBirthdayArr = strBirthday.split('/');
  var birthYear = strBirthdayArr[0];
  var birthMonth = strBirthdayArr[1];
  var birthDay = strBirthdayArr[2];
  //获取当前日期
  var d = new Date();
  var nowYear = d.getFullYear();
  var nowMonth = d.getMonth() + 1;
  var nowDay = d.getDate();
  if (nowYear == birthYear) {
    returnAge = 0; //同年 则为0岁
  } else {
    var ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        var dayDiff = nowDay - birthDay; //日之差
        if (dayDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      } else {
        var monthDiff = nowMonth - birthMonth; //月之差
        if (monthDiff < 0) {
          returnAge = ageDiff - 1;
        } else {
          returnAge = ageDiff;
        }
      }
    } else {
      returnAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return returnAge; //返回周岁年龄
}

method.getUuiD = (randomLength) => {
  return Number(Math.random().toString().substr(2, randomLength) + Date.now()).toString(36)
}
//生成从minNum到maxNum的随机数
method.randomNum = (minNum, maxNum) => {
  return Math.round(Math.random() * (maxNum - minNum) + minNum)
}

// 无文本格式
method.getText = (str) => {
  if (str) {
    let words = str.replace(/<[^<>]+>/g, "").replace(/&nbsp;/gi, "")
    str = words.replace(/\s/g, "")
  }
  return str;
}
// 分割数组
method.splitArray = (array, chunkSize) => {
  const result = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    result.push(chunk);
  }
  return result;
}

export default method
